﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using Microsoft.Phone.Shell;
using VodafoneWP7.Resources;
using System.Windows.Media.Imaging;
using System.Diagnostics;
using Microsoft.Phone.Tasks;
using System.Threading;






namespace VodafoneWP7
{
    public static class LayoutConfiguration
    {
        public static int AccountsListWidth;
        public static int MessagesListWidth=435;
        public static int ServicesListWidth;
        public static int AdsListWidth;

    }

    public partial class MainPage : PhoneApplicationPage
    {
        MainPageStatus status;
        public static List<Account> Accounts;
        List<AMessageService> Services;
        Account selectedAccount;
        SavedOptions SavedOptions;
        // Constructor
        bool isTrial;

        ApplicationBarIconButton B_send_message, B_delete_current_message, B_cancel_sending_message, settings, B_edit_message_list,
            B_delete_message_list, B_cancel_edit_message_list,B_add_profile;


        public MainPage()
        {
            status = new MainPageStatus();
            InitializeComponent();
            //sendbutton.IsEnabled = false;
            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;
            Accounts_ListBox.ItemsSource = App.ViewModel.AccountsItems;
            Services_ListBox.ItemsSource = App.ViewModel.ServicesItems;
            Messages_ListBox.ItemsSource = App.ViewModel.MessagesItem;

            Accounts = Storage.LoadAccounts();
            Services = MessaggingServices.AvailableServices;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
            isTrial = App.isTrial();
            SavedOptions = Storage.LoadSavedOptions();
            
            if (!isTrial)
            {
                settings = new ApplicationBarIconButton() { Text = Strings.Settings, IsEnabled = true };

                if (App.CurrentTheme == App.Theme.Dark)
                    settings.IconUri = new Uri("\\Images\\dark\\appbar.feature.settings.rest.png", UriKind.Relative);
                else
                    settings.IconUri = new Uri("\\Images\\light\\appbar.feature.settings.rest.png", UriKind.Relative);
                settings.Click += OpenSettings_Button_Click;
            }

            var prefix = App.CurrentTheme == App.Theme.Dark?"\\Images\\dark\\":"\\Images\\light\\";

            B_send_message = new ApplicationBarIconButton(new Uri(prefix+"appbar.send.rest.png", UriKind.Relative)) { Text = Strings.Send, IsEnabled = true };            
            B_delete_current_message = new ApplicationBarIconButton(new Uri(prefix+"appbar.delete.rest.png", UriKind.Relative)) { Text = Strings.Delete, IsEnabled = true };
            B_cancel_sending_message = new ApplicationBarIconButton(new Uri(prefix+"appbar.cancel.rest.png", UriKind.Relative)) { Text = Strings.Delete, IsEnabled = true };

            B_edit_message_list = new ApplicationBarIconButton(new Uri(prefix + "appbar.edit.rest.png", UriKind.Relative)) { Text = "asd", IsEnabled = true };
            B_delete_message_list = new ApplicationBarIconButton(new Uri(prefix + "appbar.delete.rest.png", UriKind.Relative)) { Text = Strings.Delete, IsEnabled = true };
            B_cancel_edit_message_list = new ApplicationBarIconButton(new Uri(prefix+"appbar.cancel.rest.png", UriKind.Relative)) { Text = Strings.Delete, IsEnabled = true };
            B_add_profile = new ApplicationBarIconButton(new Uri(prefix + "appbar.new.rest.png", UriKind.Relative)) { Text = Strings.CreateAccount, IsEnabled = true };


            B_send_message.Click += new EventHandler((object o, EventArgs ea) => { Send_Button_Click(o, null); });
            B_delete_current_message.Click += new EventHandler((object o, EventArgs ea) => { Delete_Button_Click(o, null); });
            B_cancel_sending_message.Click += new EventHandler((object o, EventArgs ea) => { Cancel_Button_Click(o, null); });
            B_edit_message_list.Click += new EventHandler(B_edit_message_list_Click);
            B_delete_message_list.Click += new EventHandler(B_delete_message_list_Click);
            B_cancel_edit_message_list.Click += new EventHandler(B_cancel_edit_message_list_Click);
            B_add_profile.Click += new EventHandler(B_add_profile_Click);


            OrientationChanged += new EventHandler<OrientationChangedEventArgs>(MainPage_OrientationChanged);
            MainPage_OrientationChanged(null, null);
        }

        void B_add_profile_Click(object sender, EventArgs e)
        {
            PhoneApplicationService.Current.State.Remove("AccountManagementType");
            PhoneApplicationService.Current.State.Add("AccountManagementType", AccountManagementType.Create);
            NavigationService.Navigate(new Uri("/AccountsPage.xaml", UriKind.Relative));

        }

        void B_cancel_edit_message_list_Click(object sender, EventArgs e)
        {
            deleting_messages = false;
            for (int i = 0; i < App.ViewModel.MessagesItem.Count; i++)
            {
                var item = App.ViewModel.MessagesItem[i];
                item.deleting = false;
                App.ViewModel.MessagesItem.Insert(i, item);
                App.ViewModel.MessagesItem.RemoveAt(i + 1);
            }
            ApplicationBar.Buttons.Clear();
            ApplicationBar.Buttons.Add(B_edit_message_list);
        }

        void B_delete_message_list_Click(object sender, EventArgs e)
        {
            //TODO: DELETE MESSAGES FROM HISTORY
            deleting_messages = false;
            for (int i = 0; i < App.ViewModel.MessagesItem.Count; i++)
            {
                var item = App.ViewModel.MessagesItem[i];
                item.deleting = false;
                if (item.delete)
                {
                    App.ViewModel.MessagesItem.RemoveAt(i);
                    item.related_acount.messages.Remove(item.related_message);
                    i--;
                }
                else
                {
                    App.ViewModel.MessagesItem.Insert(i, item);
                    App.ViewModel.MessagesItem.RemoveAt(i + 1);
                }
            }
            Storage.SaveAccounts(Accounts);
            ApplicationBar.Buttons.Clear();
            ApplicationBar.Buttons.Add(B_edit_message_list);
        }

        void B_edit_message_list_Click(object sender, EventArgs e)
        {
            
            deleting_messages = true;
            for (int i = 0; i < App.ViewModel.MessagesItem.Count; i++ )
            {
                var item = App.ViewModel.MessagesItem[i];
                item.deleting = true;
                App.ViewModel.MessagesItem.Insert(i, item);
                App.ViewModel.MessagesItem.RemoveAt(i + 1);
            }
            Messages_ListBox.Margin = new Thickness(0, 0, 0, 0);
            ApplicationBar.Buttons.Clear();
            ApplicationBar.Buttons.Add(B_cancel_edit_message_list);
            ApplicationBar.Buttons.Add(B_delete_message_list);

        }

        public string test = "sdasdas";
        public int list_width=135;
        void MainPage_OrientationChanged(object sender, OrientationChangedEventArgs e)
        {
            if (Orientation == PageOrientation.Landscape || Orientation==PageOrientation.LandscapeLeft || Orientation==PageOrientation.LandscapeRight)
            {
                SMSGrid.RowDefinitions[2].Height = new GridLength(71);
                Receiver_Label.Margin = new Thickness(15, 20, 0, 0);
                SMS_Number_Area.Width = 440;

                Pivot_SMS.Margin = new Thickness(10, -10, 10, 0);
                Pivot_Services.Margin = new Thickness(10, -10, 10, 0);
                Pivot_Sent.Margin = new Thickness(10, -10, 10, 0);
                Pivot_Accounts.Margin = new Thickness(10, -10, 10, 0);

                LayoutConfiguration.MessagesListWidth = 600;
                LayoutConfiguration.ServicesListWidth = 520;
                LayoutConfiguration.AdsListWidth = 470;

                CreditsPanel.Visibility = System.Windows.Visibility.Collapsed;
                CreditsPanelLandscape.Visibility = System.Windows.Visibility.Visible;
                image1.Visibility = System.Windows.Visibility.Collapsed;
                image1Landscape.Visibility = System.Windows.Visibility.Visible;

                PivotControl_SelectionChanged(null, null);
                //Search_Button.Margin = new Thickness(90, 12, 15, 0);
            }
            else 
            {
                SMSGrid.RowDefinitions[2].Height = new GridLength(95);
                Receiver_Label.Margin = new Thickness(15, 0, 0, 0);
                //Search_Button.Margin = new Thickness(0, 12, 15, 0);
                SMS_Number_Area.Width = 380;

                LayoutConfiguration.MessagesListWidth = 435;
                LayoutConfiguration.ServicesListWidth = 370;
                LayoutConfiguration.AdsListWidth = 310;

                CreditsPanel.Visibility = System.Windows.Visibility.Visible;
                CreditsPanelLandscape.Visibility = System.Windows.Visibility.Collapsed;
                image1.Visibility = System.Windows.Visibility.Visible;
                image1Landscape.Visibility = System.Windows.Visibility.Collapsed;

                Pivot_SMS.Margin = new Thickness(10, -0, 10, 10);
                Pivot_Services.Margin = new Thickness(10, -0, 10, 10);
                Pivot_Sent.Margin = new Thickness(10, -0, 10, 10);
                Pivot_Accounts.Margin = new Thickness(10, -0, 10, 10);

                PivotControl_SelectionChanged(null, null);
            }

            App.ViewModel.AdsItems.Clear();
            foreach (var app in ApplicationState.state.applications)
            {
                App.ViewModel.AdsItems.Add(new AdsViewModel() { Name = app.name, Description = app.description, ID = app.id, ImageUri = new Uri(app.imageUri, UriKind.Absolute) });
            }

            App.ViewModel.ServicesItems.Clear();
            for (int i = 0; i < Services.Count; i++)
                App.ViewModel.ServicesItems.Add(new ServiceItemViewModel()
                {
                    Name = Services[i].GetName(),
                    ImageUri = Services[i].GetImageUri(),
                    Description = Services[i].GetDescription()
                });

        }
                
        public static string WebBrowserHTML = "";
        // Load data for the ViewModel Items

        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {           
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
                new Thread(new ThreadStart(
                () =>
                {
                    WebConnection.updateOtherProduct(() =>
                    {
                        Dispatcher.BeginInvoke(() =>
                        {
                            App.ViewModel.AdsItems.Clear();
                            foreach (var app in ApplicationState.state.applications)
                            {
                                App.ViewModel.AdsItems.Add(new AdsViewModel() { Name = app.name, Description = app.description, ID = app.id, ImageUri = new Uri(app.imageUri, UriKind.Absolute) });
                            }
                            ApplicationState.SaveState();
                        });
                    });
                })).Start();
            }
            DisableProgressBar();
            
            AccountsChoose_Context_Menu.Items.Clear();
            var item = new MenuItem() { Header = Strings.All };
            item.Click += AccountChooser_Context_Menu_Click;
            AccountsChoose_Context_Menu.Items.Add(item);

            if (Accounts.Count == 0)
            {
                Account_Area.Text = Strings.CreateAccount;

            }
            else
            {
                Account_Area.Text = Strings.ChooseAnAccount;
                Accounts_Context_Menu.Items.Clear();
                for (int i = 0; i < Accounts.Count; i++)
                {
                    MenuItem menuItem = new MenuItem() { Header = Accounts[i].Name };
                    menuItem.Click += Account_Context_Menu_Click;
                    Accounts_Context_Menu.Items.Add(menuItem);


                    item = new MenuItem() { Header = Accounts[i].Name };
                    item.Click += AccountChooser_Context_Menu_Click;
                    AccountsChoose_Context_Menu.Items.Add(item);
                }
            }
            if (App.CurrentTheme == App.Theme.Dark)
            {
                Search_Button.Source = new BitmapImage(new Uri("\\Images\\dark\\appbar.feature.search_circled.rest.png", UriKind.Relative));
                //Search_Button_Circle.Source = new BitmapImage(new Uri("\\Images\\dark\\appbar.basecircle.rest.png", UriKind.Relative));
            }
            else
            {
                Search_Button.Source = new BitmapImage(new Uri("\\Images\\light\\appbar.feature.search_circled.rest.png", UriKind.Relative));
                //Search_Button_Circle.Source = new BitmapImage(new Uri("\\Images\\light\\appbar.basecircle.rest.png", UriKind.Relative));
            }



            //Search_Button.MouseLeftButtonUp+=new MouseButtonEventHandler(Search_Button_MouseLeftButtonDown);
        }

        private void OpenCredits_Button_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/CreditsPage.xaml", UriKind.Relative));
        }

        private void OpenSettings_Button_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/SettingsPage.xaml", UriKind.Relative));
        }
        
        void chooser_Completed(object sender, Microsoft.Phone.Tasks.PhoneNumberResult e)
        {
            if (e.TaskResult == Microsoft.Phone.Tasks.TaskResult.OK)
            {
                SMS_Number_Area.Text = e.PhoneNumber.ToString();
            }
        }

        public static CookieContainer cookieJar;
        public static BitmapImage bitmapImage;
        //private ConnectionQueue connections;

        private void Cancel_Button_Click(object sender, RoutedEventArgs e)
        {
            DisableProgressBar();
            if (currentMessageService != null)
                currentMessageService.Stop();
            //if (selectedAccount != null)
            //    selectedAccount.messaggingService.Stop();
            //Cancel_Button.Visibility = System.Windows.Visibility.Collapsed;
            //Send_Button.Visibility = System.Windows.Visibility.Visible;
            ApplicationBar.Buttons.Remove(B_cancel_sending_message);
            ApplicationBar.Buttons.TryAdd(B_send_message);


            //Delete_Button.Visibility = System.Windows.Visibility.Visible;
            ApplicationBar.Buttons.TryAdd(B_delete_current_message);

            SMS_Message_Area.IsEnabled = true;
            SMS_Number_Area.IsEnabled = true;
            Search_Button.Visibility = System.Windows.Visibility.Visible;
            //Search_Button_Circle.Visibility = System.Windows.Visibility.Visible;
        }

        private void Send_Button_Click(object sender, RoutedEventArgs e)
        {
            if (Send_SMS_Message())
            {
                ApplicationBar.Buttons.TryAdd(B_cancel_sending_message);
                ApplicationBar.Buttons.Remove(B_send_message);
                ApplicationBar.Buttons.Remove(B_delete_current_message);


                SMS_Message_Area.IsEnabled = false;
                SMS_Number_Area.IsEnabled = false;
                Search_Button.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        public static AMessageService currentMessageService;
        private bool Send_SMS_Message()
        {
            if (selectedAccount == null)
                return false;
            //test();

            EnableProgressBar();
            //status.number = "3491580861";
            //status.message = "test";
            status.message = SMS_Message_Area.Text;
            status.number = SMS_Number_Area.Text;
            //selectedAccount.messaggingService.SendSMS(selectedAccount, status, (bi) => { bitmapImage = bi; OpenCodeVerificationPage(); },
            //    ErrorInTask, WebBrowserRequired, TaskCompleted, Dispatcher);
            if (currentMessageService == null)
                currentMessageService = MessaggingServices.GetService(selectedAccount.MessagingService);
            currentMessageService.SendSMS(selectedAccount, status, (bi) => { bitmapImage = bi; OpenCodeVerificationPage(); },
                ErrorInTask, WebBrowserRequired, TaskCompleted, Dispatcher);
            return true;
        }
        
        private void Number_Area_GotFocus(object sender, RoutedEventArgs e)
        {
            if (SMS_Number_Area.Text == "")
            {
                var chooser = new Microsoft.Phone.Tasks.PhoneNumberChooserTask();
                chooser.Completed += new EventHandler<Microsoft.Phone.Tasks.PhoneNumberResult>(chooser_Completed);
                chooser.Show();
            }
        }

        private void Search_Button_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                var chooser = new Microsoft.Phone.Tasks.PhoneNumberChooserTask();
                chooser.Completed += new EventHandler<Microsoft.Phone.Tasks.PhoneNumberResult>(chooser_Completed);
                chooser.Show();
            }
            catch (Exception) { }

        }

        public void TaskCompleted()
        {
            DisableProgressBar();
            selectedAccount.messages.Add(new Message() { type = MessageType.SMS, text = status.message, dateTime = DateTime.Now, number = status.number });
            Storage.SaveAccounts(Accounts);
        }

        public void OpenCodeVerificationPage()
        {
            DisableProgressBar();
            NavigationService.Navigate(new Uri("/CodeVerificationPage.xaml", UriKind.Relative));
        }

        public static string NavigationUri;
        public void WebBrowserRequired(string html, string uri)
        {
            WebBrowserHTML = html;
            NavigationUri = uri;
            DisableProgressBar();
            NavigationService.Navigate(new Uri("/WebBrowserPage.xaml", UriKind.Relative));
        }

        public void ErrorInTask(string message)
        {
            DisableProgressBar(message);
        }
        #region ACTIVATE_DEACTIVATE

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            status.number = SMS_Number_Area.Text;
            status.message = SMS_Message_Area.Text;
            PhoneApplicationService.Current.State.Remove("MainPageStatus");
            PhoneApplicationService.Current.State.Add("MainPageStatus", status);

            PhoneApplicationService.Current.State.Remove("SelectedAccount");
            if (selectedAccount != null)
                PhoneApplicationService.Current.State.Add("SelectedAccount", selectedAccount);


        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            SavedOptions = Storage.LoadSavedOptions();
            if (PhoneApplicationService.Current.State.ContainsKey("MainPageStatus"))
            {
                status = (MainPageStatus)(PhoneApplicationService.Current.State["MainPageStatus"]);
                PhoneApplicationService.Current.State.Remove("MainPageStatus");
            }
            else
                status = new MainPageStatus();
            if (PhoneApplicationService.Current.State.ContainsKey("SelectedAccount"))
            {
                selectedAccount = (Account)(PhoneApplicationService.Current.State["SelectedAccount"]);
                PhoneApplicationService.Current.State.Remove("SelectedAccount");
                Account_Area.Text = selectedAccount.Name;
            }
            else
                selectedAccount = null;

            Accounts = Storage.LoadAccounts();

            DisableProgressBar();

            PivotControl_SelectionChanged(null, null);
            //Cancel_Button.Visibility = System.Windows.Visibility.Collapsed;
            //Send_Button.Visibility = System.Windows.Visibility.Visible;


            SMS_Message_Area.IsEnabled = true;
            SMS_Number_Area.IsEnabled = true;
            Search_Button.Visibility = System.Windows.Visibility.Visible;

        }
        #endregion

        private void AdControl_AdControlError(object sender, Microsoft.Advertising.Mobile.UI.ErrorEventArgs e)
        {
            Debug.WriteLine(e.ErrorDescription);
            Debug.WriteLine(e.ToString());
        }

        #region PROGRESS_BAR

        private void EnableProgressBar()
        {
            ToggleProgressBar.IsEnabled = true;
            ToggleProgressBar.IsIndeterminate = true;
            ToggleProgressBar.Visibility = System.Windows.Visibility.Visible;
        }
        private void DisableProgressBar()
        {
            ToggleProgressBar.IsEnabled = false;
            ToggleProgressBar.IsIndeterminate = false;
            ToggleProgressBar.Visibility = System.Windows.Visibility.Collapsed;
        }
        private void DisableProgressBar(string message)
        {
            MessageBox.Show(message);
            ToggleProgressBar.IsEnabled = false;
            ToggleProgressBar.IsIndeterminate = false;
            ToggleProgressBar.Visibility = System.Windows.Visibility.Collapsed;
        }

        #endregion

        private void Delete_Button_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show(Strings.AreYouSure, "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                SMS_Number_Area.Text = "";
                SMS_Message_Area.Text = "";
                status.message = "";
                status.number = "";
            }
        }

        #region ACCOUNT_POP_UP

        private void GestureListener1_Tap(object sender, GestureEventArgs e)
        {
            try
            {
                if (Accounts.Count == 0)
                {
                    PhoneApplicationService.Current.State.Remove("AccountManagementType");
                    PhoneApplicationService.Current.State.Add("AccountManagementType", AccountManagementType.Create);
                    NavigationService.Navigate(new Uri("/AccountsPage.xaml", UriKind.Relative));
                    return;
                }
                Border border = sender as Border;
                ContextMenu contextMenu = ContextMenuService.GetContextMenu(border);
                if (contextMenu.Parent == null)
                {
                    contextMenu.IsOpen = true;
                }
            }
            catch (Exception) { }
        }

        private void Account_Context_Menu_Click(object sender, RoutedEventArgs e)
        {
            //diceType1 = GetDiceType(sender, diceType1);
            //DiceTypeText1.Text = GetDiceTypeString(diceType1);
            try
            {
                MenuItem item = (MenuItem)sender;
                string s = (string)item.Header;

                for (int i = 0; i < Accounts.Count; i++)
                {
                    if (s == Accounts[i].Name)
                    {
                        Account_Area.Text = s;
                        selectedAccount = Accounts[i];
                        if (!selectedAccount.SavePassword && selectedAccount.TemporaryPassword == "")
                        {
                            PhoneApplicationService.Current.State.Remove("AccountManagementType");
                            PhoneApplicationService.Current.State.Add("AccountManagementType", AccountManagementType.AskPassword);
                            //PhoneApplicationService.Current.State.Remove("ActiveAccount");
                            //PhoneApplicationService.Current.State.Add("ActiveAccount", selectedAccount);
                            NavigationService.Navigate(new Uri("/AccountsPage.xaml", UriKind.Relative));
                            //return;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
        }

        #endregion

        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (SavedOptions.ConfirmOnExit)
                if (MessageBox.Show(Strings.AreYouSuretoExit, "", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                    e.Cancel = true;
        }

        private void PivotControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ApplicationBar.Buttons.Clear();
            deleting_messages = false;

            if (PivotControl.SelectedItem == Pivot_Accounts)
            {
                App.ViewModel.AccountsItems.Clear();
                for (int i = 0; i < Accounts.Count; i++)
                    App.ViewModel.AccountsItems.Add(new AccountItemViewModel()
                    {
                        Name = Accounts[i].Name,
                        Service = MessaggingServices.GetService(Accounts[i].MessagingService).GetName(),
                        Description = GetAccountDescription(Accounts[i])
                    });
                if (!isTrial)
                {
                    ApplicationBar.Buttons.TryAdd(B_add_profile);
                }
            }
            else if (PivotControl.SelectedItem == Pivot_SMS)
            {
                ApplicationBar.Buttons.TryAdd(B_send_message);
                //Delete_Button.Visibility = System.Windows.Visibility.Visible;
                ApplicationBar.Buttons.TryAdd(B_delete_current_message);
            }
            else if(PivotControl.SelectedItem ==  Pivot_Services)
            {

            }       
            else if (PivotControl.SelectedItem == Pivot_Sent)
            {
                if (AccountsChoose_Context_Menu.Items.Count > 0)
                    AccountChooser_Context_Menu_Click(AccountsChoose_Context_Menu.Items[0], null);
                ApplicationBar.Buttons.TryAdd(B_edit_message_list);
            }
            else if (PivotControl.SelectedItem != Pivot_Sent)
            {
                //App.ViewModel.MessagesItem.Clear();
                AccountChooser_Area.Text = Strings.ChooseAnAccount;

            }
        }

        private string GetAccountDescription(Account account)
        {
            var s = Strings.Available;

            //int sms = account.messaggingService.GetRemainingAvailableSMS(account);
            //int mms = account.messaggingService.GetRemainingAvailableMMS(account);

            int sms = MessaggingServices.GetService(account.MessagingService).GetRemainingAvailableSMS(account);
            //int mms = MessaggingServices.GetService(account.serviceType).GetRemainingAvailableMMS(account);
            bool sms_available = false;
            if (sms > 0 && sms != int.MaxValue)
            {
                s += " SMS: " + sms;
                sms_available = true;
            }
            else if (sms == int.MaxValue)
            {
                s += " SMS: " + Strings.NoLimit;
                sms_available = true;
            }

            //if (mms > 0 && mms != int.MaxValue)
            //{
            //    if (sms_available)
            //        s += " -";
            //    s += " MMS: " + sms;
            //}
            //else if (mms == int.MaxValue)
            //{
            //    if (sms_available)
            //        s += " -";
            //    s += " MMS: " + Strings.NoLimit;
            //}
            //if (sms > 0 && sms != int.MaxValue && mms > 0 && mms != int.MaxValue)
            //    s += " SMS: " + sms + " - " + "MMS: " + mms;
            //else if (sms > 0 && sms != int.MaxValue)
            //    s += " SMS: " + sms;

            //else if (mms > 0 && mms != int.MaxValue)
            //    s += " MMS: " + mms;



            return s;
        }

        private void Accounts_ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                AccountItemViewModel item = (AccountItemViewModel)Accounts_ListBox.SelectedItem;
                for (int i = 0; i < Accounts.Count; i++)
                    if (Accounts[i].Name == item.Name)
                    {
                        selectedAccount = Accounts[i];

                        PhoneApplicationService.Current.State.Remove("AccountManagementType");
                        PhoneApplicationService.Current.State.Add("AccountManagementType", AccountManagementType.Edit);

                        NavigationService.Navigate(new Uri("/AccountsPage.xaml", UriKind.Relative));
                        break;
                    }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
        }

        bool deleting_messages = false;
        private void Messages_ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Messages_ListBox.SelectionChanged -= Messages_ListBox_SelectionChanged;
            try
            {
                var sel = (MessageItemViewModel)Messages_ListBox.SelectedItem;
                if (deleting_messages) sel.delete = !sel.delete;
                else sel.short_message = !sel.short_message;
                var index = Messages_ListBox.SelectedIndex;
                App.ViewModel.MessagesItem.Insert(index, sel);
                App.ViewModel.MessagesItem.RemoveAt(index+1);
               
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            Messages_ListBox.SelectionChanged += Messages_ListBox_SelectionChanged;
        }

        private void AccountChooser_Context_Menu_Click(object sender, RoutedEventArgs e)
        {

            try
            {
                MenuItem item = (MenuItem)(sender==null?AccountsChoose_Context_Menu.Items[0]:sender);
                string s = (string)item.Header;
                App.ViewModel.MessagesItem.Clear();
                if (s == Strings.All)
                {
                    App.ViewModel.MessagesItem.Clear();
                    Accounts.Select(acc => acc.messages.Select(m => new { m, acc })).Aggregate((out_list, mess) => out_list.Concat(mess).ToList())
                        .OrderByDescending(m => m.m.dateTime).ToList().ForEach(m =>
                            App.ViewModel.MessagesItem.Add(new MessageItemViewModel()
                                {
                                    Destination = m.m.number,
                                    deleting = deleting_messages,
                                    Date = m.m.dateTime.ToString(),
                                    Message = m.m.text,
                                    Type = Message.GetMessageTypeString(m.m.type),
                                    related_acount = m.acc,
                                    related_message = m.m
                                }));
                            
                    //int a = 0;
                    //while (a++ < 100)
                    //{
                    //    App.ViewModel.MessagesItem.Add(new MessageItemViewModel()
                    //    {
                    //        Destination = "3491234567",
                    //        Date = DateTime.Now.ToString(),
                    //        deleting = deleting_messages,
                    //        Message = "Testo corto",
                    //        Type = ""
                    //    });
                    //    App.ViewModel.MessagesItem.Add(new MessageItemViewModel()
                    //    {
                    //        Destination = "34957434675",
                    //        Date = DateTime.Now.ToString(),
                    //        deleting = deleting_messages,
                    //        Message = "Mesi passati sui libri per preparare la tesi di laurea e, dopo la discussione, la tesi può finire nell'immondizia. E' accaduto all'Università di Bari, dove sono state ritrovate circa 30 tesi di laurea in un cestino tra lattine di bevande e confezioni vuote delle merendine",
                    //        Type = ""
                    //    });
                    //    App.ViewModel.MessagesItem.Add(new MessageItemViewModel()
                    //    {
                    //        Destination = "3498657534",
                    //        Date = DateTime.Now.ToString(),
                    //        Message = "Testo corto",
                    //        deleting = deleting_messages,
                    //        Type = ""
                    //    });
                    //    App.ViewModel.MessagesItem.Add(new MessageItemViewModel()
                    //    {
                    //        Destination = "7665876898",
                    //        Date = DateTime.Now.ToString(),
                    //        deleting = deleting_messages,
                    //        Message = "Aperto il bando per 31 borse di studio finalizzate allo svolgimento di un tirocinio formativo in Spagna, Polonia o Irlanda: le domande possono essere presentate fino al 12 giugno",
                    //        Type = ""
                    //    });
                    //}
                   
                }
                else
                {
                    Accounts.Where(a=>a.Name==s).Select(acc => acc.messages.Select(m => new { m, acc })).Aggregate((out_list, mess) => out_list.Concat(mess).ToList())
                    .OrderByDescending(m => m.m.dateTime).ToList().ForEach(m =>
                        App.ViewModel.MessagesItem.Add(new MessageItemViewModel()
                        {
                            Destination = m.m.number,
                            deleting = deleting_messages,
                            Date = m.m.dateTime.ToString(),
                            Message = m.m.text,
                            Type = Message.GetMessageTypeString(m.m.type),
                            related_acount = m.acc,
                            related_message = m.m
                        }));

                    //for (int j = 0; j < Accounts.Count; j++)
                    //{
                    //    if (s == Accounts[j].name)
                    //    {
                    //        Account acc = Accounts[j];

                    //        var service = MessaggingServices.GetService(acc.serviceType).GetName();
                    //        for (int i = 0; i < acc.messages.Count; i++)
                    //        {
                    //            var m = acc.messages[i];

                    //            App.ViewModel.MessagesItem.Add(new MessageItemViewModel()
                    //            {
                    //                Destination = m.number,
                    //                Date = m.dateTime.ToString(),
                    //                deleting=deleting_messages,
                    //                Message = m.text,
                    //                Type = Message.GetMessageTypeString(m.type)
                    //            });
                    //        }
                    //        break;
                    //    }
                    //}
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
        }
        
        private void Suggestion_Button_Click(object sender, RoutedEventArgs e)
        {
            EmailComposeTask etc = new EmailComposeTask();
            etc.Subject = Strings.Title + " - " + Strings.Suggestion;
            etc.To = "luckmanera@gmail.com";
            etc.Show();
        }


        #region ADS
        

        public static bool showProducts = false;
        
        private void Ads_List_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (Ads_List.SelectedItem == null)
                return;
            AdsViewModel ads = Ads_List.SelectedItem as AdsViewModel;
            Ads_List.SelectedItem = null;
            if (ads.Name != Strings.OtherProducts && ads.ID != "")
                OpenMarket(ads.ID);


        }


        private void Ads1_Button_Click(object sender, RoutedEventArgs e)
        {
            PivotControl.SelectedItem = AdsPivot_Name;
        }

        private void OpenMarket(string ID)
        {

            MarketplaceDetailTask marketplaceDetailTask = new MarketplaceDetailTask();
            marketplaceDetailTask.ContentIdentifier = ID;
            marketplaceDetailTask.Show();
        }
        #endregion

    }






    public static class Extensions
    {
        public static void TryAdd<T> (this System.Collections.IList self, T item)
        {
            try
            {
                self.Add(item);
            }
            catch (Exception) { }
        }
    }
}